<script setup>
import { ref, onMounted, watch, computed, onBeforeMount } from 'vue'
import { generateUUID, go2Link, go2Router, copyJSON, getDeviceType, bgColors, isPhone, uploadFile, isNotEmpty, isEmpty, saveUser2Db } from '@/plugins/util.js'
import { useRouter } from 'vue-router'
import { useUser } from '@/composition/useUser'
import { useConfirm } from '@/composition/useConfirm'
import { useToast } from '@/composition/useToast'
import defaultIcon from "@/assets/img/default-icon.png";

const router = useRouter();
const { user, getSearchEnginesDefault } = useUser();
const { showConfirm } = useConfirm()
const { successToast, errorToast, infoToast, warningToast } = useToast();



const breadcrumbs = ref([
    {
        text: '主页',
        disabled: false,
        to: 'home'
    },
    {
        text: '搜索引擎',
        disabled: true,
        to: 'search'
    },
])
const itemIsDefault = ref(0)
const resetDialog = ref(false)
const delDialog = ref(false)
const activeSeachEnginIndex = ref(-1)
const openItem = ref({})
const editDialog = ref(false)
const valid = ref(false)
const notNullRules = ref([
    v => !!v || '不能为空'
    // v => v.length <= 10 || 'Name must be less than 10 characters',
])

const iconSelectShow = ref(false)
const index = ref(-1)
const options = ref({
    delayOnTouchOnly: true,  //开启触摸延时
    direction: 'vertical',   //拖动方向
    delay: 500,              //延时时长
    touchStartThreshold: 3,  //防止某些手机过于敏感(3~5 效果最好)
    dragClass: 'drag',    //格式为简单css选择器的字符串，目标拖动过程中添加
    animation: 500    // ms, 动画速度运动项目排序时，' 0 ' -没有动画。
})
const uploadEle = ref()

const searchEngineList = ref([]);
const searchSugSwitch = ref(true)
const searchHisSwitch = ref(true)

// watch(searchSugSwitch, () => {
//     saveSearchInfo2Db()
// })

// watch(searchHisSwitch, () => {
//     saveSearchInfo2Db()
// })

const saveSearchInfo2Db = () => {
    user.value.extInfo.search.engines = searchEngineList.value
    user.value.extInfo.search.sugSwitch = searchSugSwitch.value
    user.value.extInfo.search.hisSwitch = searchHisSwitch.value

    saveUser2Db();
}

onMounted(() => {
    const userSearchInfo = copyJSON(user.value.extInfo.search)
    searchEngineList.value = userSearchInfo.engines
    searchSugSwitch.value = userSearchInfo.sugSwitch
    searchHisSwitch.value = userSearchInfo.hisSwitch

})

const resetConfirm = () => {
    showConfirm({ content: '确认恢复默认吗？' }).then(() => {
        resetSearchEngine();
    }).catch(() => { })
}
const checkItem = (selectedIdx) => {
    if (searchEngineList.value.length < selectedIdx) {
        return;
    }
    searchEngineList.value.forEach(element => {
        element.isDefault = false; // 全部变成不选择
    });
    searchEngineList.value[selectedIdx].isDefault = true;
    saveSearchInfo2Db()
}
const openAddModel = () => {
    openItem.value = {
        isDefault: true, // 默认选中
        url: '',
        name: '',
        icon: defaultIcon,
        uuid: generateUUID()
    }
    activeSeachEnginIndex.value = -1;
    editDialog.value = true;
}
const openEditModel = (index) => {
    activeSeachEnginIndex.value = index;
    editDialog.value = true;
    openItem.value = copyJSON(searchEngineList.value[index]);
}
const openDelModel = (index) => {
    activeSeachEnginIndex.value = index;
    showConfirm({ content: '确认删除吗？' }).then(() => {
        delSearchEngine();
    }).catch(() => { })
}
const resetSearchEngine = () => {
    searchEngineList.value = getSearchEnginesDefault()
    saveSearchInfo2Db()
}

const saveSearchEngine = () => {
    if (openItem.value.url.indexOf('%s') < 0) {
        warningToast('搜索地址中必须含有%s')
        return;
    }

    editDialog.value = false;
    if (activeSeachEnginIndex.value === -1) {
        if (searchEngineList.value.length >= 5) {
            // this.$toast.warning('搜索引擎最多设置5个，请修改或者删除其中一个再操作');
            warningToast('索引擎最多设置5个，请修改或者删除多余的再操作')
            return;
        }
        searchEngineList.value.forEach(element => {
            element.isDefault = false; // 全部变成不选择
        });
        searchEngineList.value.push(openItem.value);
    } else {
        // this.searchEngineList.value[this.activeSeachEnginIndex] = this.openItem;
        if (searchEngineList.value.length > 5) {
            warningToast('索引擎最多设置5个，请修改或者删除多余的再操作')
            return;
        }
        searchEngineList.value[activeSeachEnginIndex.value] = openItem.value
    }
    saveSearchInfo2Db()
}
const upLoadSuccess = (url) => {
    openItem.value.icon = url;
}
const delSearchEngine = () => {
    // 当前这个是否被选中，选中不能删除
    if (searchEngineList.value[activeSeachEnginIndex.value].isDefault) {
        warningToast('请先取消选中!')
        return;
    }
    if (searchEngineList.value.length == 1) {
        warningToast('请至少保留一个!')
        return;
    }
    searchEngineList.value.splice(activeSeachEnginIndex.value, 1);
    saveSearchInfo2Db()

}


</script>

<template>
    <div class="h-container">
        <div class="m-5">
            <header class="border-l-8 border-green-500 py-3 pl-4 bg-green-200 rounded italic tracking-widest">
                <span class="text-indigo-500 cursor-pointer" @click="go2Router('home')">主页</span>
                <span class="mx-2">/</span>
                <span>搜索引擎</span>
            </header>

            <div class="flex mt-4 w-full py-3 pl-4 bg-green-200 text-sm rounded text-green-900 tracking-widest mb-2">
                <div class="mr-2">搜索建议</div>
                <div class="flex">
                    <div class="flex justify-center items-center">
                        <input @click="searchSugSwitch = true, saveSearchInfo2Db()" :checked="searchSugSwitch" type="radio"
                            name="searchSugSwitchCheck" class="mr-2" id="searchSugSwitchTrue" />
                        <label for="searchSugSwitchTrue" class="cursor-pointer">打开</label>
                    </div>
                    <div class="flex justify-center items-center cursor-pointer ml-2">
                        <input @click="searchSugSwitch = false, saveSearchInfo2Db()" :checked="!searchSugSwitch"
                            type="radio" name="searchSugSwitchCheck" class="mr-2" id="searchSugSwitchFalse" />
                        <label for="searchSugSwitchFalse" class="cursor-pointer">关闭</label>
                    </div>
                </div>
            </div>
            <div class="flex mt-4 w-full py-3 pl-4 bg-green-200 text-sm rounded text-green-900 tracking-widest mb-2">
                <div class="mr-2">搜索历史</div>
                <div class="flex">
                    <div class="flex justify-center items-center">
                        <input @click="searchHisSwitch = true, saveSearchInfo2Db()" :checked="searchHisSwitch" type="radio"
                            name="searchHisSwitchCheck" class="mr-2" id="searchHisSwitchTrue" />
                        <label for="searchHisSwitchTrue" class="cursor-pointer">打开</label>
                    </div>
                    <div class="flex justify-center items-center cursor-pointer ml-2">
                        <input @click="searchHisSwitch = false, saveSearchInfo2Db()" :checked="!searchHisSwitch"
                            type="radio" name="searchHisSwitchCheck" class="mr-2" id="searchHisSwitchFalse" />
                        <label for="searchHisSwitchFalse" class="cursor-pointer">关闭</label>
                    </div>
                </div>
            </div>


            <section class="mt-4">

                <transition enter-active-class="animated fadeInUp faster" tag="div">
                    <div>

                        <div class="w-full py-3 pl-4 bg-green-200 text-sm rounded text-gray-500 tracking-widest">
                            <p>下面是预置的一些搜索引擎，点击可以设置默认，也可以自己添加，关键字使用 %s 替换</p>
                        </div>


                        <div class="h-12 w-full flex justify-center items-center my-2 space-x-3">
                            <button type="button" @click="openAddModel()" class="btn btn-primary">
                                新增一个
                            </button>
                            <button type="button" @click="resetConfirm()" class="btn btn-warning">
                                恢复默认
                            </button>
                        </div>


                        <div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-5">
                            <div v-for="(item, index) in searchEngineList" :key="item.uuid" :index="index"
                                class="shadow-md">
                                <div>
                                    <div class="w-full h-40 bg-contain bg-center bg-no-repeat flex items-end cursor-pointer rounded relative"
                                        @click="checkItem(index)" :style="{
                                            backgroundImage: 'url(' + item.icon + ')'
                                        }">
                                        <div class="text-white w-full p-2 text-sm bg-black bg-opacity-20 truncate"
                                            :title="item.name">
                                            {{ item.name }}
                                        </div>

                                        <div :style="{
                                            height: item.isDefault ? '100%' : 0
                                        }"
                                            class="flex justify-center items-center opacity-40 absolute w-full bg-black rounded transition-all duration-200">
                                            <i v-show="item.isDefault" class="fa fa-check text-5xl text-white"></i>
                                        </div>
                                    </div>
                                    <div class="h-12 w-full flex justify-end items-center pr-2 space-x-3">
                                        <button type="button" @click="openEditModel(index)" class="btn btn-primary">
                                            编辑
                                        </button>
                                        <button type="button" @click="openDelModel(index)" class="btn btn-warning">
                                            删除
                                        </button>
                                    </div>
                                </div>
                            </div>

                        </div>
                    </div>
                </transition>

            </section>

            <!--            :style-set="{top:'20%',maxWidth:'800px'}"-->

            <h-pop :show="editDialog" @close="editDialog = false" :style-set="{ top: '10%', maxWidth: '800px' }">
                <template #header>
                    <div>编辑</div>
                </template>
                <template #main>
                    <div class="grid grid-cols-1 md:gap-y-5">
                        <h-input v-model="openItem.url" label="搜索链接：" placeholder="搜索链接，关键字使用 %s 代替"></h-input>
                        <h-input v-model="openItem.name" label="搜索名称："></h-input>
                        <h-input v-model="openItem.icon" label="搜索Icon：">
                            <template #right>
                                <div class="btn btn-primary w-20 py-2.5 flex items-center justify-center text-lg cursor-pointer"
                                    @click="uploadEle.click()">
                                    <i class="fas fa-cloud-upload-alt"></i>
                                </div>
                                <h-upload ref="uploadEle" @upLoadSuccess="upLoadSuccess"></h-upload>
                            </template>
                        </h-input>

                        <div class="flex justify-center items-center mt-2 md:mt-0">
                            <img :src="openItem.icon" class="h-20 cursor-pointer transition"
                                @click="Utils.go2Link(openItem.icon, '_blank')">
                        </div>
                    </div>
                </template>
                <template #footer>
                    <div class="h-12 w-full flex justify-end items-center pr-2 space-x-4">
                        <button type="button" @click="editDialog = false" class="btn btn-secondary">
                            关闭
                        </button>
                        <button type="button" @click="saveSearchEngine()" class="btn btn-primary">
                            保存
                        </button>
                    </div>
                </template>
            </h-pop>
        </div>
    </div>
</template>


<style scoped >
.v-card--reveal {
    bottom: 0;
    opacity: .5;
    position: absolute;
    width: 100%;
}
</style>
